<template>
	<a-modal
		v-model:open="modalVisible"
		title="VIP 续费"
		:width="400"
		@ok="handleRenew"
		@cancel="handleCancel"
		:confirmLoading="loading"
		okText="立即续费"
		cancelText="取消"
	>
		<div class="renew-modal-content">
			<div class="renew-info">
				<p>使用新的兑换码延长您的VIP时间。续费后，VIP时间将在当前基础上累加。</p>
			</div>

			<a-form :model="renewForm" layout="vertical">
				<a-form-item label="续费兑换码" required>
					<a-input
						v-model:value="renewForm.renewCode"
						placeholder="请输入续费兑换码"
						size="large"
						:maxlength="32"
						@keyup.enter="handleRenew"
						:disabled="loading"
					/>
					<div class="form-tip">输入有效的兑换码来延长VIP会员时间</div>
				</a-form-item>
			</a-form>
		</div>
	</a-modal>
</template>

<script lang="ts" setup>
import { ref, reactive, watch } from 'vue'
import { message } from 'ant-design-vue'
import { renewVip } from '@/api/vipRedeemCodeController'

interface Props {
	visible: boolean
}

interface Emits {
	(e: 'update:visible', value: boolean): void
	(e: 'success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const modalVisible = ref(false)
const loading = ref(false)

const renewForm = reactive({
	renewCode: '',
})

// 监听props变化
watch(
	() => props.visible,
	(newVal) => {
		modalVisible.value = newVal
	},
	{ immediate: true }
)

// 监听modal状态变化
watch(modalVisible, (newVal) => {
	emit('update:visible', newVal)
})

// 处理续费
const handleRenew = async () => {
	if (!renewForm.renewCode.trim()) {
		message.error('请输入续费兑换码')
		return
	}

	loading.value = true
	try {
		const res = await renewVip({
			vipCode: renewForm.renewCode.trim(),
		})

		if (res.data.code === 0 && res.data.data === true) {
			message.success('续费成功！您的VIP时间已延长！')
			emit('success')
			handleCancel()
		} else {
			message.error(res.data.message || '续费失败，请检查兑换码是否正确')
		}
	} catch (error: any) {
		console.error('续费失败:', error)
		const errorMessage = error?.response?.data?.message || error?.message || '续费失败，请检查兑换码是否正确'
		message.error(errorMessage)
	} finally {
		loading.value = false
	}
}

// 取消操作
const handleCancel = () => {
	modalVisible.value = false
	renewForm.renewCode = ''
}
</script>

<style scoped lang="scss">
.renew-modal-content {
	.renew-info {
		margin-bottom: 20px;
		padding: 12px;
		background: #e6f7ff;
		border: 1px solid #91d5ff;
		border-radius: 6px;

		p {
			margin: 0;
			color: #0050b3;
			font-size: 14px;
			line-height: 1.5;
		}
	}

	.form-tip {
		color: #666;
		font-size: 12px;
		margin-top: 4px;
	}
}
</style>
